package IOTWeb.com.handler;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.utils.LogSet;
import IOTWeb.com.utils.Utils;

public class CodeeditHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		new Thread(new Runnable() {
			@Override
            public void run() {
				try {	
					LogSet.logger.info("url: " + exchange.getRequestURI().toString());
					Utils utils = new Utils();
		    		String result = "";
					String sql = "";
					String body;
		    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		    		java.sql.Date sDate = null;
					String queryString = exchange.getRequestURI().getQuery();//get:获得url后面的值
					Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
					OutputStream os = exchange.getResponseBody();
					PrintStream out = new PrintStream(os);
					DataInputStream di = new DataInputStream(exchange.getRequestBody());
					if((body = di.readLine()) != null) {
						body=new String(body.getBytes("iso-8859-1"),"UTF-8");
						sql = body;
					}
					Headers headers = exchange.getRequestHeaders();
					Headers responseHeaders = exchange.getResponseHeaders();
					utils.setResponseJson(responseHeaders);
					List<String> tocken = headers.get("token");
					if(tocken != null && !tocken.isEmpty() && utils.haveTocken(tocken)) {
						if (exchange.getRequestURI().toString().substring(0, 14).equals("/codeedit/edit")) {
							Integer i = utils.editcont(sql);
							if(i!=0)
								result = utils.addResult("\"数据库操作成功！\"", "ok");
							else
								result = utils.addResult("数据库操作失败！", "error");
						}else if (exchange.getRequestURI().toString().substring(0, 16).equals("/codeedit/select")) {
							JSONArray type = utils.selectcont(sql);
							if(type==null)
								result = utils.addResult("查询错误", "error");
							else
								result = utils.addResult(type.toString(), "ok");
						}else
							result = utils.addResult("404!!!接口错误", "error");
						byte[] bytes = result.getBytes("utf-8");
						int len = bytes.length;
						exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, len);
						out.write(bytes, 0, bytes.length);
						out.flush();
						out.close();
					}else {
						utils.tockenError(exchange);
					}
				}catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
}
